package com.dpfmanage.api.project.dpfmanage.util;

import com.dpfmanage.api.project.dpfmanage.enums.DelFlagEnum;
import com.dpfmanage.api.common.utils.SecurityUtils;
import com.dpfmanage.api.project.dpfmanage.util.orderlyuuid.SequentialUuidHexGeneratorEnum;
import com.dpfmanage.api.project.system.domain.SysUser;

import java.lang.reflect.Field;
import java.util.Date;
import java.util.Objects;

public class EntityUtil {


    public static <T> void addInit(T t) {
        if (Objects.isNull(t)) {
            return;
        }

        try {
            Class<?> aClass = t.getClass();
            Class<?> superclass = aClass.getSuperclass();
            Field updateTime = superclass.getDeclaredField("updateTime");
            updateTime.setAccessible(true);
            updateTime.set(t, new Date());
            Field createTime = superclass.getDeclaredField("createTime");
            createTime.setAccessible(true);
            createTime.set(t, new Date());
            Field delFlag = superclass.getDeclaredField("delFlag");
            delFlag.setAccessible(true);
            delFlag.set(t, DelFlagEnum.NOT_DEL.getCode());

            Field createBy = superclass.getDeclaredField("createBy");
            createBy.setAccessible(true);
            SysUser user = SecurityUtils.getLoginUser().getUser();
            Long userId = user.getUserId();
            createBy.set(t, userId);
            Field updateBy = superclass.getDeclaredField("updateBy");
            updateBy.setAccessible(true);
            updateBy.set(t, userId);
            Field id = aClass.getDeclaredField("id");
            id.setAccessible(true);
            String idValue = SequentialUuidHexGeneratorEnum.Instance.generateNoSeq();
            id.set(t, idValue);
        } catch (NoSuchFieldException | IllegalAccessException e) {
        }
    }

    public static <T> void updateInit(T t) {
        if (Objects.isNull(t)) {
            return;
        }
        try {
            Class<?> aClass = t.getClass();
            Class<?> superclass = aClass.getSuperclass();
            Field updateTime = superclass.getDeclaredField("updateTime");
            updateTime.setAccessible(true);
            updateTime.set(t, new Date());
            SysUser user = SecurityUtils.getLoginUser().getUser();
            Long userId = user.getUserId();
            Field updateBy = superclass.getDeclaredField("updateBy");
            updateBy.setAccessible(true);
            updateBy.set(t, userId);
        } catch (NoSuchFieldException | IllegalAccessException e) {
        }
    }
}
